<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" :size="size">
                <el-row>
                    <el-col>
                        <el-form-item label="" prop="type">
                            <el-select v-model="condition.search.type" placeholder="活动类型">
                                <el-option
                                    v-for="item in this.CONST.member_card_activity_options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="showAddDialog">新增</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="exportExcel" v-if="!memberCardId">导出</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            id="mainTable"
            :data="tableData"
            :size="size"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="60">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="name"
                width="100px"
                label="活动名称">
            </el-table-column>
            <el-table-column
                prop="description"
                width="150px"
                label="活动说明">
            </el-table-column>
            <el-table-column
                prop="type"
                width="80px"
                :formatter="formatType"
                label="活动类型">
            </el-table-column>
            <el-table-column
                prop="levelNames"
                width="120px"
                label="适用等级">
            </el-table-column>
            <el-table-column
                prop="givePoints"
                label="赠送积分">
            </el-table-column>
            <el-table-column
                prop="giveCouponNames"
                width="120px"
                label="赠送优惠券">
            </el-table-column>
            <el-table-column
                prop="startTime"
                width="95px"
                label="开始时间">
            </el-table-column>
            <el-table-column
                prop="endTime"
                width="95px"
                label="结束时间">
            </el-table-column>
            <el-table-column
                prop="joinLimit"
                label="次数限制">
            </el-table-column>
            <el-table-column
                prop="status"
                :formatter="formatStatus"
                label="状态">
            </el-table-column>
            <el-table-column
                prop="festivalName"
                label="节日名称">
            </el-table-column>
            <el-table-column
                prop="festivalDate"
                label="节日日期">
            </el-table-column>
            <el-table-column
                prop="totalQuantity"
                label="总数量">
            </el-table-column>
            <el-table-column
                prop="remainQuantity"
                label="剩余数量">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
            <el-table-column
                prop="createBy"
                label="谁创建的">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="80px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="35%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px" :size="size">
                <el-form-item label="活动类型">
                    <el-select v-model="addOrUpdateForm.type"
                               placeholder="活动类型">
                        <el-option
                            v-for="item in this.CONST.member_card_activity_options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="活动名称">
                    <el-input v-model="addOrUpdateForm.name"
                              placeholder="活动名称"></el-input>
                </el-form-item>
                <el-form-item label="活动说明">
                    <el-input v-model="addOrUpdateForm.description" type="textarea" placeholder="活动说明"></el-input>
                </el-form-item>
                <el-form-item label="开始时间">
                    <el-date-picker
                        v-model="addOrUpdateForm.startTime"
                        type="datetime"
                        placeholder="开始时间"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :picker-options="this.CONST.DATE_TIME_PICKER_OPTIONS"
                        align="right">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker
                        v-model="addOrUpdateForm.endTime"
                        type="datetime"
                        placeholder="结束时间"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :picker-options="this.CONST.DATE_TIME_PICKER_OPTIONS"
                        align="right">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="节日名称" v-if="addOrUpdateForm.type == 'FESTIVAL_GIFT'">
                    <el-input v-model="addOrUpdateForm.festivalName"
                              placeholder="节日名称"></el-input>
                </el-form-item>
                <el-form-item label="节日日期" v-if="addOrUpdateForm.type == 'FESTIVAL_GIFT'">
                    <el-date-picker
                        v-model="addOrUpdateForm.festivalDate"
                        type="date"
                        placeholder="节日日期"
                        value-format="yyyy-MM-dd"
                        align="right">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="总数量">
                    <el-input v-model="addOrUpdateForm.totalQuantity"
                              placeholder="总数量"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="赠送积分">
                    <el-input v-model="addOrUpdateForm.givePoints"
                              placeholder="赠送积分"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="赠送优惠券">
                    <el-button @click="selectCouponDialogVisible = true" size="mini" type="plain"
                               v-if="selectedCoupon.length == 0">
                        点击选择
                    </el-button>
                    <el-button @click="selectCouponDialogVisible = true" size="mini" type="success" v-else>
                        已选择{{ selectedCoupon.length }}个优惠券
                    </el-button>
                    <div class="form-tips">
                        请选择需要赠送的优惠券！
                    </div>
                </el-form-item>
                <el-form-item label="适用等级">
                    <el-button @click="selectLevel" size="mini" type="plain" v-if="selectedLevel.length == 0">
                        点击选择
                    </el-button>
                    <el-button @click="selectLevel" size="mini" type="success" v-else>
                        已选择{{ selectedLevel.length }}种等级
                    </el-button>
                    <div class="form-tips">
                        请选择合适的等级，只有满足等级才能参加该活动！
                    </div>
                </el-form-item>
                <el-form-item label="次数限制">
                    <el-input v-model="addOrUpdateForm.joinLimit" placeholder="参加限制"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                    <div class="form-tips">
                        最多只能参加几次！
                    </div>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="addOrUpdateForm.status"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addOrUpdateDialogVisible = false" :size="size">取 消</el-button>
                <el-button @click="addOrUpdateConfirm" type="primary" :size="size">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="选择优惠券" width="50%" :visible.sync="selectCouponDialogVisible" append-to-body>
            <coupon ref="coupon"></coupon>
            <div slot="footer" class="dialog-footer">
                <el-button @click="selectCouponDialogVisible = false" :size="size">取 消</el-button>
                <el-button @click="selectCouponConfirm" type="primary" :size="size">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="选择等级" width="50%" :visible.sync="selectLevelDialogVisible" append-to-body>
            <el-table :data="levelData" size="mini" header-cell-class-name="tableHeaderStyle"
                      @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="name" label="等级名称"></el-table-column>
                <el-table-column prop="discount" label="等级折扣"></el-table-column>
                <el-table-column prop="createTime" label="创建时间"></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button @click="selectLevelDialogVisible = false" :size="size">取 消</el-button>
                <el-button @click="selectLevelConfirm" type="primary" :size="size">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addMemberCardActivity,
    deleteMemberCardActivity,
    getMemberCardActivityByPage,
    getMemberCardLevelByPage,
    updateMemberCardActivity
} from '@/api/api'
import Coupon from "@/component/Coupon";

export default {
    name: "member-card-activity",
    components: {Coupon},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            // 优惠券选择
            selectCouponDialogVisible: false,
            selectedCoupon: [],

            // 等级选择
            levelData: [],
            selectLevelDialogVisible: false,
            selectedLevel: [],
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        memberCardId: String,
        size: {
            type: String,
            default: 'small'
        },
    },
    methods: {
        handleSelectionChange(val) {
            this.selectedLevel = val;
        },
        selectLevel() {
            this.selectLevelDialogVisible = true;
            if (this.levelData.length == 0) {
                this.getLevelData();
            }
        },
        selectLevelConfirm() {
            this.selectLevelDialogVisible = false
            if (this.levelData.length > 0) {
                this.addOrUpdateForm.levelIds = this.selectedLevel.map(item => item.id).join(",");
                this.addOrUpdateForm.levelNames = this.selectedLevel.map(item => item.name).join(",");
            }
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        selectCouponConfirm() {
            this.selectedCoupon = this.$refs.coupon.couponSelected;
            this.selectCouponDialogVisible = false;

            if (this.selectedCoupon.length > 0) {
                this.addOrUpdateForm.giveCouponIds = this.selectedCoupon.map(item => item.id).join(",");
                this.addOrUpdateForm.giveCouponNames = this.selectedCoupon.map(item => item.title).join(",");
            }
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatType: function (row, column, cellValue) {
            for (const elem of this.CONST.member_card_activity_options) {
                if (elem.value == cellValue) {
                    return elem.label;
                }
            }
            return "未知";
        },
        formatStatus: function (row, column, cellValue) {
            if (!cellValue) {
                return "";
            }
            if (cellValue == '0') {
                return "关闭";
            } else if (cellValue == '1') {
                return "开启";
            } else {
                return "未知";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
            this.addOrUpdateForm.memberCardId = this.memberCardId;
            this.$set(this.addOrUpdateForm, "status", true)
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        add: function () {
            addMemberCardActivity(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            updateMemberCardActivity(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteMemberCardActivity({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取表格数据
        getData: function () {
            this.condition.search.memberCardId = this.memberCardId;
            getMemberCardActivityByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
            });
        },
        // 获取等级数据
        getLevelData: function () {
            let condition = {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            };
            condition.search.memberCardId = this.memberCardId;
            getMemberCardLevelByPage(condition).then(data => {
                this.levelData = data.body.rows;
            });
        }
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
